//
//  LeGetRequestBase.m
//  LeNetwork
//
//  Created by CaiLei on 2/20/14.
//  Copyright (c) 2014 Le123. All rights reserved.
//

#import "LeGetRequestBase.h"
#import "GTMNSDictionary+URLArguments.h"

@implementation LeGetRequestBase {
    ASIHTTPRequest *_request;
}

- (void)startRequest {
    NSString *url = [self generateFullUrl];
    _request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    DDLogInfo(@"%@",url);
    _request.shouldContinueWhenAppEntersBackground = YES;
    _request.requestMethod = @"GET";

    @weakify(self);
    [_request setCompletionBlock:^{
        @strongify(self); if (!self) return;
        NSString *retString = [[NSString alloc] initWithData:self->_request.responseData encoding:NSUTF8StringEncoding];
        [self dealWithResponseJson:retString andError:nil];
    }];
    
    [_request setFailedBlock:^{
        @strongify(self); if (!self) return;
        [self dealWithResponseJson:nil andError:self->_request.error];
    }];
    
    [_request startAsynchronous];
}

- (void)stopRequest {
    [_request clearDelegatesAndCancel];
}

- (void)dealWithResponseJson:(NSString *)aJson andError:(NSError *)aError {
    DDLogError(@"no concrete implementation for base request: %@", aJson);
}

- (NSString *)generateFullUrl {
    NSAssert(!isEmpty(self.urlHead), @"没有指定Url");
    NSString *url = self.urlHead;
    NSDictionary *paramDict = [self toDictionary];
    if (!isEmpty(paramDict)) {
        url = [url stringByAppendingString:@"?"];
        url = [url stringByAppendingString:[paramDict gtm_httpArgumentsString]];
    }
    return url;
}

@end
